<template>
  <div class="image-upload">
    <a-upload
      v-model:file-list="fileList"
      :customRequest="customUpload"
      list-type="picture-card"
      @preview="handlePreview"
      @remove="handleRemove"
    >
      <div v-if="fileList.length < maxCount">
        <plus-outlined />
        <div style="margin-top: 8px">{{ uploadText }}</div>
      </div>
    </a-upload>

    <a-modal
      :open="previewVisible"
      :title="previewTitle"
      :footer="null"
      @cancel="closePreview"
    >
      <img alt="preview" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed } from 'vue';
import { useImageUpload } from '#/hooks/useImageUpload';

const props = defineProps({
  modelValue: {
    type: String,
    default: '[]',
  },
  maxCount: {
    type: Number,
    default: 8,
  },
  uploadText: {
    type: String,
    default: '上传图片',
  },
  uploadField: {
    type: String,
    default: 'filed',
  },
});

const emit = defineEmits(['update:modelValue']);

const {
  fileList,
  previewVisible,
  previewImage,
  previewTitle,
  handlePreview,
  customUpload,
  handleRemove,
  closePreview,
} = useImageUpload(
  computed(() => props.modelValue),
  (value) => emit('update:modelValue', value),
  {
    maxCount: props.maxCount,
    field: props.uploadField,
  },
);
</script>

<style scoped>
.image-upload {
  margin-top: 10px;
}

.image-upload :deep(.ant-upload-select-picture-card) {
  width: 104px;
  height: 104px;
  margin-right: 8px;
  margin-bottom: 8px;
}
</style>
